import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/api/index.dart';
import '../../../common/models/index.dart';

/// 活动编辑页面控制器
class ActivityEditController extends GetxController {
  // ==================== 表单模型 ====================
  late final Rx<ActivityEditForm> editForm;
  final isSubmitting = false.obs;
  
  @override
  void onInit() {
    super.onInit();
    _initParameters();
  }
  
  /// 初始化参数
  void _initParameters() {
    try {
      final args = Get.arguments as Map<String, dynamic>?;
      
      if (args != null) {
        final id = args['activityId'] as int? ?? 0;
        final title = args['title'] as String? ?? '';
        final details = args['details'] as String? ?? '';
        
        editForm = ActivityEditForm(
          activityId: id,
          activityTitle: title,
          activityDetails: details,
        ).obs;
        
        debugPrint('📝 活动编辑页面 - ID: $id, 标题: $title');
      }
    } catch (e) {
      debugPrint('❌ 参数初始化失败: $e');
    }
  }
  
  /// 保存活动编辑
  Future<void> saveActivity() async {
    if (isSubmitting.value) return;
    
    // 验证表单
    if (!editForm.value.isValid) {
      final titleError = editForm.value.validateTitle();
      final detailsError = editForm.value.validateDetails();
      
      debugPrint('⚠️ 表单验证失败');
      debugPrint('   标题错误: $titleError');
      debugPrint('   详情错误: $detailsError');
      return;
    }
    
    // 检查是否有变更
    if (!editForm.value.hasChanges) {
      debugPrint('⚠️ 没有变更，无需保存');
      Get.back();
      return;
    }
    
    isSubmitting.value = true;
    
    try {
      debugPrint('💾 保存活动编辑');
      debugPrint('   活动ID: ${editForm.value.activityId}');
      debugPrint('   标题: ${editForm.value.activityTitle}');
      
      final response = await ActivityApi.editActivity(
        activityId: editForm.value.activityId,
        activityTitle: editForm.value.activityTitle.trim(),
        activityDetails: editForm.value.activityDetails.trim(),
      );
      
      if (response.isSuccess) {
        debugPrint('✅ 活动编辑成功');
        
        // 延迟返回，让用户看到成功状态
        await Future.delayed(const Duration(milliseconds: 500));
        Get.back(result: true);
      } else {
        debugPrint('❌ 活动编辑失败: ${response.message}');
      }
    } catch (e) {
      debugPrint('❌ 保存活动异常: $e');
    } finally {
      isSubmitting.value = false;
    }
  }
}

